package com.alili.springbooteditor.controller;

import com.alili.springbooteditor.dao.CommentsDao;
import com.alili.springbooteditor.dao.EditorsDao;
import com.alili.springbooteditor.entities.comments;
import com.alili.springbooteditor.entities.editors;
import com.alili.springbooteditor.service.EditorService;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@Controller
public class editorController {
    private static final String UPLOADED_FOLDER = "/usr/img/blog/";
    @Autowired
    EditorsDao editorsDao;
    @Autowired
    EditorService editorService;
    @Autowired
    CommentsDao commentsDao;
    //普通用户来到写页面
    @GetMapping("/editor")
    public String toWritePage(){
        return "write";
    }
    //提交写好的内容
    @PostMapping("/submit")
    public String write(editors editor){
        editorsDao.save(editor);
        return "redirect:/index";
    }
    //管理员来到写页面
    @GetMapping("/main/editor")
    public String tomainWritePage(){
        return "manage/write";
    }
    //提交写好的内容
    @PostMapping("/main/submit")
    public String mainwrite(editors editor){
        editorsDao.save(editor);
        return "redirect:/main";
    }

    //普通用户显示全文
    @GetMapping("/detail/{id}")
    public String ShowDetail(@RequestParam(defaultValue = "0",value = "currentPage") int  pageNum,@PathVariable("id") Integer id,comments comment,
                             ModelMap modelMap,ModelMap modelMap2,ModelMap modelMap3,ModelMap modelMap4,ModelMap modelMap5){
        editors oneArt = editorsDao.getOneArticle(id);
        modelMap.addAttribute("artdet",oneArt);
        editors preEditor = editorService.getPreEditor(id);
        editors nextEditor = editorService.getNextEditor(id);
        modelMap2.addAttribute("pre",preEditor);
        modelMap3.addAttribute("next",nextEditor);
        //展示评论
        Page<comments> page = commentsDao.getCommentsPage(id, pageNum);
        List<comments> allComments=page.getContent();
        modelMap4.addAttribute("pages",page);
        modelMap5.addAttribute("comments",allComments);
        return "detail";
    }
    //管理员显示全文
    @GetMapping("/main/detail/{id}")
    public String ShowMainDetail(@RequestParam(defaultValue = "0",value = "currentPage") int  pageNum,@PathVariable("id") Integer id,comments comment,
                                 ModelMap modelMap,ModelMap modelMap2,ModelMap modelMap3,ModelMap modelMap4,ModelMap modelMap5){
        editors oneArt = editorsDao.getOneArticle(id);
        modelMap.addAttribute("artdet",oneArt);
        editors preEditor = editorService.getPreEditor(id);
        editors nextEditor = editorService.getNextEditor(id);
        modelMap2.addAttribute("pre",preEditor);
        modelMap3.addAttribute("next",nextEditor);
        //展示评论
        Page<comments> page = commentsDao.getCommentsPage(id, pageNum);
        List<comments> allComments=page.getContent();
        modelMap4.addAttribute("pages",page);
        modelMap5.addAttribute("comments",allComments);

        return "manage/detail";
    }

//普通用户提交评论
    @PostMapping("/detail/{id}")
    public String SubmitCommentAndShowDetail(@RequestParam(defaultValue = "0",value = "currentPage") int  pageNum,@PathVariable("id") Integer id,comments comment,
                                             ModelMap modelMap,ModelMap modelMap2,ModelMap modelMap3,ModelMap modelMap4,ModelMap modelMap5){
        //展示文章
        editors oneArt = editorsDao.getOneArticle(id);
        modelMap.addAttribute("artdet",oneArt);
        editors preEditor = editorService.getPreEditor(id);
        editors nextEditor = editorService.getNextEditor(id);
        modelMap2.addAttribute("pre",preEditor);
        modelMap3.addAttribute("next",nextEditor);
        //保存评论
        commentsDao.save(comment);
        //展示评论
        Page<comments> page = commentsDao.getCommentsPage(id, pageNum);
        List<comments> allComments=page.getContent();
        modelMap4.addAttribute("pages",page);
        modelMap5.addAttribute("comments",allComments);

        return "detail";
    }
    //管理员添加评论
    @PostMapping("main/detail/{id}")
    public String mainSubmitCommentAndShowDetail(@RequestParam(defaultValue = "0",value = "currentPage") int  pageNum,@PathVariable("id") Integer id,comments comment,
                                             ModelMap modelMap,ModelMap modelMap2,ModelMap modelMap3,ModelMap modelMap4,ModelMap modelMap5){
        //展示文章
        editors oneArt = editorsDao.getOneArticle(id);
        modelMap.addAttribute("artdet",oneArt);
        editors preEditor = editorService.getPreEditor(id);
        editors nextEditor = editorService.getNextEditor(id);
        modelMap2.addAttribute("pre",preEditor);
        modelMap3.addAttribute("next",nextEditor);
        //保存评论
        commentsDao.save(comment);
        //展示评论
        Page<comments> page = commentsDao.getCommentsPage(id, pageNum);
        List<comments> allComments=page.getContent();
        modelMap4.addAttribute("pages",page);
        modelMap5.addAttribute("comments",allComments);

        return "manage/detail";
    }

    //处理图片
    @RequestMapping(value="/uploadfile",method=RequestMethod.POST)
    public void hello(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "editormd-image-file", required = false) MultipartFile attach){
        try {
            request.setCharacterEncoding( "utf-8" );
            response.setHeader( "Content-Type" , "text/html" );
            String rootPath = request.getSession().getServletContext().getRealPath("/img/blog/");
            String physicPath=UPLOADED_FOLDER;

            /**
             * 文件路径不存在则需要创建文件路径
             */
            File filePath=new File(rootPath);
            File filePath2=new File(physicPath);
            if(!filePath2.exists()){
                filePath2.mkdirs();
            }
            if(!filePath.exists()){
                filePath.mkdirs();
            }

            //最终文件名
            File realFile=new File(rootPath+File.separator+attach.getOriginalFilename());
            File realFile2=new File(physicPath+File.separator+attach.getOriginalFilename());
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);
            FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile2);

            //下面response返回的json格式是editor.md所限制的，规范输出就OK
            response.getWriter().write( "{\"success\": 1, \"message\":\"上传成功\",\"url\":\"/img/blog/" + attach.getOriginalFilename() + "\"}" );
        } catch (Exception e) {
            try {
                response.getWriter().write( "{\"success\":0}" );
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }



}


